<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <el-button type="primary" @click="showAddCate">添加分类</el-button>
      <tree-table :data="categories" :columns="columns" :selection-type="false" :expand-type="false" show-index
        index-text="#" border style="margin-top: 20px;">
        <!-- 操作插槽 -->
        <template slot="opt" scope="scope">
          <!-- 修改按钮 -->
          <el-button type="primary" icon="el-icon-edit" size="small" @click="open_editForm(scope.row.cat_id)">编辑</el-button>
          <!-- 删除按钮 -->
          <el-button type="danger" icon="el-icon-delete" size="small" @click="confirm_del(scope.row.cat_id)">删除</el-button>
        </template>
        <!-- 分类层级插槽 -->
        <template slot="level" scope="scope">
          <el-tag type="success" v-if="scope.row.cat_level==1">二级</el-tag>
          <el-tag v-if="scope.row.cat_level==0">一级</el-tag>
          <el-tag type="warning" v-if="scope.row.cat_level==2">三级</el-tag>
        </template>
        <!-- 是否有效插槽 -->
        <template slot="isOk" scope="scope">
          <i class="el-icon-error" v-if="scope.row.cat_deleted==true" style="color: red;"></i>
          <i class="el-icon-success" v-if="scope.row.cat_deleted==false" style="color:lightgreen"></i>
        </template>
      </tree-table>
      <el-pagination :page-sizes="[1, 2, 5, 10]" :page-size="5" layout="total,sizes, prev, pager, next" :total="total"
        @size-change="handleSizeChange" @current-change="handleCurrentChange">
      </el-pagination>
    </el-card>
    <!-- 添加分类 -->
    <el-dialog title="添加分类" :visible.sync="addCate" width="50%">
      <!-- 内容主体区域 -->
      <el-form label-width="100px" :rules="addCateFormRules" ref="addCateformref" :model="form">
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="form.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类：" prop="cat_pid">
          <el-cascader v-model="pid" :options="pcategories" :props="prop" clearable @change="selectChange">
          </el-cascader>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCate = false">取 消</el-button>
        <el-button type="primary" @click="submitAddCate('addCateformref')">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑分类 -->
    <el-dialog title="编辑分类" :visible.sync="editCate" width="50%">
      <!-- 内容主体区域 -->
      <el-form label-width="100px" ref="editCateformref" :model="editform">
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="editform.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCate = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      categories: [],
      // 获取父级分类的数据列表
      pcategories: [],
      // 指定级联选择器的配置对象
      prop: {
        children: 'children',
        label: 'cat_name',
        value: 'cat_id',
        checkStrictly: 'true',
        expandTrigger: 'hover'
      },
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      editform: {
        cat_id: '',
        cat_name: ''
      },
      // 选中的父级分类的id数组
      pid: [],
      total: 0,
      columns: [{
        label: '分类名称',
        prop: 'cat_name',
        width: '400px'
      }, {
        label: '是否有效',
        prop: 'cat_deleted',
        type: 'template',
        template: 'isOk'
      }, {
        label: '排序',
        prop: 'cat_level',
        type: 'template',
        template: 'level'
      }, {
        label: '操作',
        type: 'template',
        template: 'opt',
        minWidth: '300px'
      }],
      // 添加分类的弹框
      addCate: false,
      // 编辑分类的弹框
      editCate: false,
      // 添加分类
      form: {
        cat_name: '',
        // 父级分类ID 默认为0
        cat_pid: 0,
        // 默认层级为一级分类
        cat_level: 0
      },
      addCateFormRules: {
        cat_name: [{
          required: true,
          message: '请输入分类名称',
          trigger: 'blur'
        }]
      }
    }
  },
  created () {
    this.getCate()
  },
  computed: {},
  methods: {
    // 获取分类数据
    async getCate () {
      const {
        data: res
      } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类数据失败！')
      }
      this.categories = res.data.result
      this.total = res.data.total
    },
    // 监听 页码值改变事件
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getCate()
    },
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getCate()
    },
    // 获取父级分类数据
    async getPcate () {
      const {
        data: res
      } = await this.$http.get('categories', {
        type: 2
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取父级分类数据失败')
      }
      this.pcategories = res.data
      console.log(this.pcategories)
    },
    // 显示添加分类弹框
    showAddCate () {
      this.addCate = true
      this.getPcate()
    },
    // 监听级联选择器选中情况
    selectChange () {
      if (this.pid.length >= 0) {
        this.form.cat_pid = this.pid[this.pid.length - 1]
        this.form.cat_level = this.pid.length
      } else {
        console.log('未选中父级分类')
      }
    },
    // 重置表单
    resetAddForm (formName) {
      this.$refs[formName].resetFields()
      this.pid = []
      this.form.cat_pid = 0
      this.form.cat_level = 0
    },
    // 提交添加分类表单
    submitAddCate (formName) {
      // 表单预验证
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // 解构赋值 await async化简promise
          const {
            data: res
          } = await this.$http.post(
            'categories',
            this.form
          )
          if (res.meta.status !== 201) {
            this.$message.error(res.meta.msg)
            this.addCate = false
            return false
          }
          this.$message.success('添加分类成功')
          this.addCate = false
          this.getCate()
          this.resetAddForm(formName)
        } else {
          this.$message.error('添加分类失败')
          this.addCate = false
          this.resetAddForm(formName)
          return false
        }
      })
    },
    // 打开编辑弹框
    async open_editForm (id) {
      // 根据id查找分类
      const { data: res } = await this.$http.get(`categories/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('分类信息查询失败！')
      }
      this.editform = res.data
      // 打开弹框
      this.editCate = true
    },
    // 提交编辑分类的表单
    async submitEditForm () {
      const { data: res } = await this.$http.put(`categories/${this.editform.cat_id}`, {
        cat_name: this.editform.cat_name
      })
      if (res.meta.status !== 200) {
        return this.$message.error('分类信息编辑失败！')
      }
      this.editCate = false
      this.getCate()
    },
    // 删除指定分类
    async confirm_del (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      const { data: res } = await this.$http.delete(`categories/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除分类信息失败')
      }
      this.getCate()
      return this.$message.success('删除分类成功！')
    }
  }
}

</script>
<style lang="less" scoped>
  .el-cascader {
    width: 100% !important;
  }

</style>
